package bz.ziro.kanbe.controller.mng.mail;

import java.util.Date;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;
import org.slim3.datastore.Datastore;
import org.slim3.util.BeanUtil;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

import bz.ziro.kanbe.model.Mail;
import bz.ziro.kanbe.util.KeyFactory;

/**
 * メール設定の追加
 * @author Administrator
 *
 */
public class AddController extends Controller {

    @Override
    public Navigation run() {

    	String siteKeyBuf = sessionScope("siteKey");
    	String pageKeyBuf = requestScope("parentPage");

    	Mail mail = new Mail();
    	BeanUtil.copy(request, mail);
    	
    	String siteTemplateKeyBuf = requestScope("siteTemplate");
    	String pageTemplateKeyBuf = requestScope("pageTemplate");

    	Key siteKey = KeyFactory.createSiteKey(Long.valueOf(siteKeyBuf));
    	Key pageKey = KeyFactory.createPageKey(Long.valueOf(siteKeyBuf),Long.valueOf(pageKeyBuf));
    	Key siteTemplateKey = KeyFactory.createTemplateKey(Long.valueOf(siteKeyBuf),Long.valueOf(siteTemplateKeyBuf));
    	Key pageTemplateKey = KeyFactory.createTemplateKey(Long.valueOf(siteKeyBuf),Long.valueOf(pageTemplateKeyBuf));
    
    	//各種キーを設定
    	mail.setSiteKey(siteKey);
    	mail.setParentPageKey(pageKey);
    	mail.setSiteTemplateKey(siteTemplateKey);
    	mail.setPageTemplateKey(pageTemplateKey);

        //作成者情報を取得
        UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();
        mail.setCreateDate(new Date());
        mail.setCreator(user);

        //ページのキーを取得
        Key key = KeyFactory.allocateMailKey(siteKey.getId());
        mail.setKey(key);

		Datastore.put(mail);
        return null;
    }
}
